/**
 * Copyright(c) kyle.
 */
package org.example.AIO;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.ExecutionException;

/**
 * AIO客户端
 *
 * @author kyle
 * @version 1.00.00
 * @since [2020-10-19 20:12]
 * @updateUser [Kyle]
 * @updateRemark [说明本次修改内容]
 * @date [2020-10-19 20:12]
 */
public class AIOClient {
    private final AsynchronousSocketChannel client;

    public AIOClient() throws IOException {
        client = AsynchronousSocketChannel.open();
    }

    public static void main(String[] args) throws IOException {
        new AIOClient().connect("localhost", 65432);
    }

    public void connect(String host, int port) {
        client.connect(new InetSocketAddress(host, port), null, new CompletionHandler<Void, Object>() {
            @Override
            public void completed(final Void result, final Object attachment) {
                try {
                    client.write(ByteBuffer.wrap("这是一条测试数据".getBytes())).get();
                    System.out.println("已发送至服务器");
                } catch (InterruptedException pE) {
                    pE.printStackTrace();
                } catch (ExecutionException pE) {
                    pE.printStackTrace();
                }
            }

            @Override
            public void failed(final Throwable exc, final Object attachment) {
                exc.printStackTrace();
            }
        });
        final ByteBuffer bb = ByteBuffer.allocate(1024);
        client.read(bb, null, new CompletionHandler<Integer, Object>() {
            @Override
            public void completed(final Integer result, final Object attachment) {
                System.out.println("I/O操作完成" + result);
                System.out.println("获取反馈结果" + new String(bb.array()));
            }

            @Override
            public void failed(final Throwable exc, final Object attachment) {
                exc.printStackTrace();
            }
        });
        try {
            Thread.sleep(Integer.MAX_VALUE);
        } catch (InterruptedException pE) {
            pE.printStackTrace();
        }
    }
}
